//
//  UIColor+Theme.m
//  夜间模式demo
//
//  Created by aaaa on 2020/5/28.
//  Copyright © 2020 aaaa. All rights reserved.
//

#import "UIColor+Theme.h"
#import <Objc/runtime.h>

@implementation UIColor (Theme)
+(UIColor *)colorWithThemeName:(NSString *)themeName hexString:(NSString *)hexString{
    UIColor *color = [UIColor colorHexStr:hexString alpha:1.0];
    [color setName:themeName];
    return color;
}

-(void)setName:(NSString *)name{
    objc_setAssociatedObject(self, @selector(name), name, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

-(NSString *)name{
    return objc_getAssociatedObject(self,_cmd);
}

+ (UIColor *)colorHexStr:(NSString *)color alpha:(CGFloat)alpha{
    NSCharacterSet *characterSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *cString = [[color stringByTrimmingCharactersInSet:characterSet] uppercaseString];
    
    if ([cString length] < 6)
        return [UIColor clearColor];
    
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    unsigned int r, g, b;
    [[NSScanner scannerWithString:[cString substringWithRange:NSMakeRange(0, 2)]] scanHexInt:&r];
    [[NSScanner scannerWithString:[cString substringWithRange:NSMakeRange(2, 2)]] scanHexInt:&g];
    [[NSScanner scannerWithString:[cString substringWithRange:NSMakeRange(4, 2)]] scanHexInt:&b];
    return [UIColor colorWithRed:((float)r/255.f) green:((float)g/255.f) blue:((float)b/255.f) alpha:alpha];
}


@end
